//*****************************************共通类*****************************************
document.onmousedown = handleEvent;

function handleEvent(e) {
    e = e || window.event;
    var target = e.srcElement || e.currentTarget || e.target;

    if (("undefined" != typeof RxTree) && target.isMenu != true) {
        $('.rxtree').each(function(){
            if ($(this)[0].isMenu == true && $(this)[0].style.display == "block") {
                $(this).css("display", "none");
            }
        });
    }
    if ("undefined" != typeof JyyMenu && target.isMenu != true) {
        for (var i = 0; i < JyyMenu.menus.length; i++) {
            JyyMenu.menus[i].hide();
        }
    }
}

function JyyCommon() {
}

JyyCommon.disableSelection = function(target) {
    if (target) {
        if (typeof target.onselectstart) {
            target.onselectstart = function() {
                return false;
            };
        } else if (typeof target.MozUserSelect) {
            target.MozUserSelect = "none";
        } else {
            target.onmousedown = function() {
                return false;
            };
        }
    }
};

JyyCommon.toHtmlEmpty = function(value) {
    if (value == "" || value == null || value == undefined) {
        return "&nbsp;"
    } else {
        return value;
    }
};
JyyCommon.isEmpty = function(value) {
    if (value == null || value == undefined) {
        return true;
    } else if (typeof(value) == 'string' && value == "") {
        return true;
    } else {
        return false;
    }
};
JyyCommon.isEmptyRxd = function(value) {
    if (value) {
        if (value.isEmpty()) {
            return true;
        }
        return false;
    } else {
        return true;
    }
};

JyyCommon.isDateExp = function(value,style) {
	if(style == 'yyyymmdd'){
		if(value.length == 8){
			value = value.substr(0,4)+'-'+value.substr(4,2)+'-'+value.substr(6,2);
		}else if(value.length==10){
			value = value.substr(0,4)+'-'+value.substr(5,2)+'-'+value.substr(8,2);
		}else{
			return false;
		}
	}
	if(style == 'yyyy-mm-dd'){
		if(value.length!== 10){
			return false;
		}
	}
	var r = new RegExp("^[1-2]\\d{3}-(0?[1-9]||1[0-2])-(0?[1-9]||[1-2][0-9]||3[0-1])$")
        if (r.test(value) == false) {
            return false;
        } else {
            return true;
        }
};
JyyCommon.isArray = function(value) {
    return (Object.prototype.toString.call(value) === '[object Array]');
};
JyyCommon.isString = function(value) {
    return (Object.prototype.toString.call(value) === '[object String]');
};
JyyCommon.isNumber = function(value) {
    return (Object.prototype.toString.call(value) === '[object Number]');
};
JyyCommon.isDate = function(value) {
    return (Object.prototype.toString.call(value) === '[object Date]');
};
JyyCommon.isFunction = function(value) {
    return (Object.prototype.toString.call(value) === '[object Function]');
};
JyyCommon.isObject = function(value) {
    return (Object.prototype.toString.call(value) === '[object Object]');
};
JyyCommon.isBoolean = function(value) {
    return (Object.prototype.toString.call(value) === '[object Boolean]');
};
JyyCommon.getType = function(value) {
	var dataType = Object.prototype.toString.call(data).substring(8);
	dataType = dataType.substring(0, dataType.length - 1);
    return dataType;
};

JyyCommon.toEmpty = function(value) {
    if (JyyCommon.isEmpty(value)) {
        return "";
    } else {
        return value;
    }
};
JyyCommon.toDefault = function(value, defaultValue) {
    if (JyyCommon.isEmpty(value)) {
        return defaultValue;
    } else {
        return value;
    }
};
JyyCommon.ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
JyyCommon.toColName = function(value) {
    var colName = "";
    var mod = value % 26;
    var n = Math.floor(value/26);
    if (n > 0) {
        colName = JyyCommon.ALPHA.charAt(n-1) + JyyCommon.ALPHA.charAt(mod);
    } else {
        colName = JyyCommon.ALPHA.charAt(mod);
    }
    return colName;
};
JyyCommon.toColIndex = function(value) {
    var colIndex = null;
    
    if (value.length == 1) {
        colIndex = JyyCommon.ALPHA.indexOf(value);
    } else {
        colIndex = (JyyCommon.ALPHA.indexOf(value.charAt(0)) + 1) * 26 + JyyCommon.ALPHA.indexOf(value.charAt(1));
    }
    return colIndex;
};
//*****************************************日期处理类*****************************************
// 前补充0
JyyCommon.prefixZero = function(value, n) {
    var start = 30 + (""+value).length - n;
    return ("000000000000000000000000000000" + value).substring(start);
};

//*****************************************颜色处理类*****************************************
//将#XXXXXX颜色格式转换为RGB格式，并附加上透明度
JyyCommon.crgba = function(hex, opacity) {
    if( ! /#?\d+/g.test(hex) ) return hex; //如果是“red”格式的颜色值，则不转换。//正则错误，参考后面的PS内容
    var h = hex.charAt(0) == "#" ? hex.substring(1):hex,
        r = parseInt(h.substring(0,2),16),
        g = parseInt(h.substring(2,4),16),
        b = parseInt(h.substring(4,6),16),
        a = opacity;
    return "rgba(" + r + "," + g + "," + b + "," + a + ")";
}
//将RGBA格式颜色转换为RGB颜色
JyyCommon.RGBA2RGB = function(value, bgColor){
	var arr = value.replace(/(?:\(|\)|rgba|RGBA)*/g,"").split(",");
	var a = arr[3];
	//bgColor为背景颜色。默认为白色背景。白色背景下bgColor = 1;黑色背景下bgColor = 0
	if(JyyCommon.isEmpty(bgColor)){
		bgColor = 1;
	}
	var r = bgColor * (1 - a) + arr[0] * a;
	var g = bgColor * (1 - a) + arr[1] * a;
	var b = bgColor * (1 - a) + arr[2] * a;
	return "rgb(" + parseInt(r) + "," + parseInt(g) + "," + parseInt(b) + ")";
}
//将rgba格式颜色转换为十六进制
JyyCommon.RGBA2Hex = function(value){
	var arr = value.replace(/(?:\(|\)|rgba|RGBA)*/g,"").split(",");
	var colorHex = "#";
	for ( var i = 0; i < arr.length; i++) {
		var hex = "";
		if (i == arr.length - 1) {
			hex = Number(parseInt(arr[i] * 255)).toString(16);
		} else {
			hex = Number(arr[i]).toString(16);
		}
		if (hex.length == 1) {
			hex = "0" + hex;
		}
		colorHex += hex;
	}
	if (parseInt(arr[arr.length - 1] * 255) === 0) {
		return "";
	}
	return colorHex;
}
//将rgb和rgba格式颜色转换为十六进制颜色(注：形如"#ccc"格式的颜色转换成"#cccccc")
JyyCommon.formatColor = function(color){
	
	if (/^#([0-9a-fA-f]{6})$/.test(color)) {
		return color;
	} else if (/^#([0-9a-fA-f]{3})$/.test(color)) {
		var arr = color.replace(/#/,"").split("");
		var colorHex = "#";
		for ( var i = 0; i < arr.length; i++) {
			colorHex += (arr[i] + arr[i]);
		}
		return colorHex;
	} else if (/^(rgba|RGBA)/.test(color)) {
		return JyyCommon.RGBA2Hex(color);
	} else if (/^(rgb|RGB)/.test(color)){
		return color.colorHex();
	}
	
	return color;
}
JyyCommon.crgb = function(r, g, b) {
    var sr = "00" + r.toString(16);
    var sg = "00" + g.toString(16);
    var sb = "00" + b.toString(16);
    sr = sr.substring(sr.length-2).toUpperCase();
    sg = sg.substring(sg.length-2).toUpperCase();
    sb = sb.substring(sb.length-2).toUpperCase();
    return "#" + sr + sg + sb;
}

//*****************************************控件处理类*****************************************
JyyCommon.dispose = function(isAll) {
    while (this.hasChildNodes()) {
        this.removeChild(this.lastChild);
    }
    if (isAll == true) {
        var parentNode = this.parentNode;
        if (parentNode) {
            parentNode.removeChild(this);
        }
    }
};
JyyCommon.ce = function(parent, id, tagName, className) {
	var ctrl = document.createElement(tagName);
	ctrl._self = this;
	ctrl._owner = parent;
	if (id) {
		ctrl.id = id;
	}
	if (className) {
		ctrl.className = className;
	}
	if (parent) {
		parent.appendChild(ctrl);
	}
	return ctrl;
};
JyyCommon.setStyle = function(ctrl, style) {
	if (!ctrl) {
		return;
	}
    var cssText = "";
    for (var prop in style) {
        ctrl.style[prop] = style[prop];
    }
};
JyyCommon.getStyle = function(ctrl, styleName) {
	if (!ctrl) {
		return;
	}
    var style = null;
    if (getComputedStyle) {
        style = getComputedStyle(ctrl,"style")[styleName];
    } else {
        style = getStyle(ctrl,"style")[styleName];
    }
    return style;
};
JyyCommon.getEOP = function(ctrl) {
	var point = {x:0, y:0};
	if (navigator.userAgent.indexOf("Firefox") < 0) {
		point.x = point.x + ctrl.offsetLeft + parseInt(JyyCommon.getStyle(ctrl, "borderLeftWidth").replace("px",""));
		point.y = point.y + ctrl.offsetTop + parseInt(JyyCommon.getStyle(ctrl, "borderTopWidth").replace("px",""));
		var pctrl = ctrl.offsetParent;
		while (pctrl) {
			point.x = point.x + pctrl.offsetLeft + parseInt(JyyCommon.getStyle(ctrl, "borderLeftWidth").replace("px",""));
			point.y = point.y + pctrl.offsetTop + parseInt(JyyCommon.getStyle(ctrl, "borderTopWidth").replace("px",""));
			pctrl = pctrl.offsetParent;
		};
	} else {
		point.x = ctrl.offsetLeft;
		point.y = ctrl.offsetTop;
	}
	return point;
};
/* 格式化文字 */
JyyCommon.format = function(value, dataType, format) {
	if (JyyCommon.isEmpty(value) || JyyCommon.isEmpty(format)) {
		return value;
	}
	var fmtstr = format.replace(/#/g, "0");
	var ov = (""+value).replace(/,/g, "");;
	if (dataType == "number") {
		ov = parseFloat(ov);
		if (ov.toString() == "NaN") {
			return value;
		}
		if (JyyCommon.isEmpty(fmtstr)) {
			fmtstr = "0.00";
		}

		var n = fmtstr.indexOf(".");
		var fmtint = "";
		var fmtdec = "";
		if (n >= 0) {
			fmtint = fmtstr.substring(0, n);
			fmtdec = fmtstr.substring(n+1);
		} else {
			fmtint = fmtstr;
			fmtdec = "";
		}
		var isComma = false;
		n = fmtstr.indexOf(",");
		if (n >= 0) {
			isComma = true;
		}

		var valstr = "" + ov.toFixed(fmtdec.length);
		n = valstr.indexOf(".");
		var valint = "";
		var valdec = "";
		if (n >= 0) {
			valint = valstr.substring(0, n);
			valdec = valstr.substring(n+1);
		} else {
			valint = valstr;
			valdec = "";
		}
		if (valint.length == 0) {
			valint = "0";
		}
		if (valdec.length == 0) {
			valdec = "00000000".substring(0, fmtdec.length);
		} else {
			valdec = (valdec+"00000000").substring(0, fmtdec.length);
		}
		//console.log("fmt(" + fmtint + "*" + fmtdec + ")--->val(" + valint + "*" + valdec + ")");

		var result = "";
		if (isComma) {
			for (i = valint.length-1; i >= 0; i--) {
				result = valint.substring(i, i+1) + result;
				if (((valint.length - i) % 3) == 0) {
					result = (i==0?"":",") + result;
				}
			}
			result = result + (valdec.length == 0 ? "" : ("." + valdec));
		} else {
			result = valint + (valdec.length == 0 ? "" : ("." + valdec));
		}
		//console.log("value(" + value + "),format(" + format + "),result(" + result + ")");
		return result;

	} else if (dataType == "date") {
		
	}

	return ov;
};

/* 获取UUID */
JyyCommon.ALPHA_NUMBER = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
JyyCommon.getUUID = function() {
	var id = "";
	for (var i = 0; i < 16; i++) {
		var n = Math.ceil(Math.random()*35);
		id = id + JyyCommon.ALPHA_NUMBER[n];
	}
	return id;
}

/* 获取文字尺寸 */
JyyCommon.word = null;
JyyCommon.getTextSize = function(target, text) {
	if (JyyCommon.word == null) {
		JyyCommon.word = document.createElement("span");
		JyyCommon.word.className = "rxword_span";
		document.body.appendChild(JyyCommon.word);
	}
	JyyCommon.word.style.fontSize = JyyCommon.getStyle(target, "fontSize");
	JyyCommon.word.style.fontFamily = JyyCommon.getStyle(target, "fontFamily");
	JyyCommon.word.style.fontWeight = JyyCommon.getStyle(target, "fontWeight");
	JyyCommon.word.style.fontStyle = JyyCommon.getStyle(target, "fontStyle");
	JyyCommon.word.style.textDecoration = JyyCommon.getStyle(target, "textDecoration");
	JyyCommon.word.innerHTML = text;
	return {width:JyyCommon.word.offsetWidth, height:JyyCommon.word.offsetHeight};
};
JyyCommon.getTextSizeForFont = function(font, text) {
	if (this.word == null) {
		this.word = document.createElement("span");
		this.word.className = "rxword_span";
		document.body.appendChild(this.word);
	}
	this.word.style.fontSize = font.fontSize;
	this.word.style.fontFamily = font.fontName;
	this.word.style.fontWeight = font.getFontWeight();
	this.word.style.fontStyle = font.getFontStyle();
	this.word.style.textDecoration = font.getTextDecoration();
	this.word.innerHTML = text;
	return {
		width:this.word.offsetWidth, 
		height:this.word.offsetHeight
	};
}
JyyCommon.getMosuePoint = function(eX, eY, targetW, targetH) {
	var point = {x:eX, y:eY, isFullWidth:false, isFullHeight:false};
	var pageH = document.documentElement.clientHeight;
	var pageW = document.documentElement.clientWidth;
//console.log("pageX,pageY,clientWidth,clientHeight:" + pageX + "," + pageY + "," + pageW + "," + pageH);
//console.log("rect.width,rect.height:" + targetW + "," + targetH);
	if (point.y + targetH > pageH) {
		point.y = point.y - targetH - 1;
		point.y = point.y < 0 ? 0:point.y;
		point.isFullHeight = true;
	} else {
		point.y = point.y + 1;
	}
	if (point.x + targetW > pageW) {
		point.x = point.x - targetW - 1;
		point.x = point.x < 0 ? 0:point.x;
		point.isFullWidth = true;
	} else {
		point.x = point.x + 1;
	}
	return point;
};
JyyCommon.getBodyOffset = function(obj) {
	var offset = {top:0, left:0};
	while (obj) {
		if (obj.tagName && obj.tagName.toUpperCase() == "BODY") {
			break;
		}
		//TODO：如果是IE或opera浏览器需要考虑追加边框宽度
		offset.top += obj.offsetTop-obj.scrollTop;
		offset.left += obj.offsetLeft-obj.scrollLeft;
		obj = obj.offsetParent
	}
	return offset;
};

JyyCommon.parseJson = function(json) {
	if (JyyCommon.isString(json)) {
		try{
			return JSON.parse(json);
		} catch(e) {
			console.log("parse json failed!"); 
		}
	}
	return json;
}

JyyCommon.isInteger = function(value) {
	var nvalue = parseFloat(value);
	if (isNaN(value)) {
	    return false;
	} else {
		return (nvalue %1 === 0);
	}
};

//是否为正整数
JyyCommon.isPositiveInteger = function(theObj) {
  var reg = /^[0-9]+$/ ;
  if (reg.test(theObj)) {
    return true;
  }
  return false;
}

//创建Form表单
JyyCommon.createForm = function(config) {
	config = config || {};

    var url = config.url,
        method = config.method || 'GET',
        params = config.params || {},
        enctype = config.enctype || 'application/x-www-form-urlencoded';

    var form = document.createElement('form');
    form.action = url;
    form.method = method;
    form.enctype = enctype;
    //form.target = "_blank";

    for(var param in params){
        var value = params[param],
            input = document.createElement('input');

        input.type = 'hidden';
        input.name = param;
        input.value = value;

        form.appendChild(input);
    }

    return form;
}
//获取html跳转url参数
JyyCommon.getUrlParam = function(name) {
	if(JyyCommon.isEmpty(name)) return null;
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var area = window.location.search.substr(1).match(reg);
	if (area != null) {
		return unescape(area[2]);
	}else{
		return null;
	}
}
//*************************************时间格式化处理*************************************
JyyCommon.dateFtt = function(fmt,date) {
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };
  if(/(y+)/.test(fmt)){
	  fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  }
  for(var k in o){
	  if(new RegExp("("+ k +")").test(fmt)){
		  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
	  }
  }
  return fmt;   
}
JyyCommon.getNowDateString = function () {
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    if(mon<10){
        mon="0"+mon;
    }
    var date = myDate.getDate(); //获取当前日
    if(date<10){
        date="0"+date;
    }
    var hours = myDate.getHours(); //获取当前小时
    if(hours<10){
        hours="0"+hours;
    }
    var minutes = myDate.getMinutes(); //获取当前分钟
    if(minutes<10){
        minutes="0"+minutes;
    }
    var seconds = myDate.getSeconds(); //获取当前秒
    if(seconds<10){
        seconds="0"+seconds;
    }
    var now = year   + mon   + date + "_" + hours   + minutes   + seconds;
    return now;
}